package com.huluspace.chat.function;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.definition.ToolDefinition;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.List;
import java.util.Map;
import java.util.function.Function;



@Component
public class WeatherNow implements ToolCallback {
  @Value("${weather.api.key}")
  private String apiKey;

  // 构造器方式注入WebClient
  private final WebClient webClient;
  public WeatherNow(WebClient webClient) {
    this.webClient = webClient;
  }

  @Override
  public @NonNull ToolDefinition getToolDefinition() {
    // 定义一个符合JSON Schema的字符串
    String inputSchema = """
        {
          "type": "object",
          "properties": {
            "city": {
              "type": "string",
              "description": "城市中文名，例如：北京、上海"
            }
          },
          "required": ["city"]
        }
        """;
    return ToolDefinition.builder()
        .name("get_current_weather")
        .description("根据城市名称获取当前天气")
        .inputSchema(inputSchema) // 注意这里是 String
        .build();
  }

  @Override
  public @NonNull String call(@NonNull String toolInput) {
    try {
      ObjectMapper mapper = new ObjectMapper();
      JsonNode node = mapper.readTree(toolInput);
      String city = node.get("city").asText();
      Response result = weather(city);
      return mapper.writeValueAsString(result);
    } catch (Exception e) {
      throw new RuntimeException("WeatherNow tool call failed", e);
    }
  }

  public record Response(String location, String date, String weather, double temperature) {}

  public Response weather(String cityName) {
    WeatherResponse response =  webClient.get()
        .uri(uriBuilder -> uriBuilder
            .path("/v7/weather/now")
            .queryParam("location", cityToCode(cityName))
            .build()) // 构建请求地址（uri）
        .header("X-QW-Api-Key", apiKey) // 在请求头中设置API-KEY
        .retrieve() // 表示发送请求并准备获取响应
        .bodyToMono(WeatherResponse.class) // 将响应体反序列化为Response对象
        .block(); // 同步方式返回，等待请求完成并返回具体数据
    return new Response(
        cityName,
        response.getUpdateTime(),
        response.getNow().getText(),
        Double.parseDouble(response.getNow().getTemp())
    );
  }


  private String cityToCode(String city){
    // 创建内部类来映射JSON结构
    record CityLocation(
        String name,
        String id,
        String lat,
        String lon,
        String adm2,
        String adm1,
        String country,
        String tz,
        String utcOffset,
        String isDst,
        String type,
        String rank,
        String fxLink
    ) {}
    record LocationResponse(
        String code,
        java.util.List<CityLocation> location,
        Object refer
    ) {}

    try {
        // 直接获取并解析响应为LocationResponse对象
        LocationResponse response = webClient.get()
            .uri(uriBuilder -> uriBuilder
                .path("/geo/v2/city/lookup")
                .queryParam("location", city)
                .queryParam("number", 1)
                .build())
            .header("X-QW-Api-Key", apiKey)
            .retrieve()
            .bodyToMono(LocationResponse.class)
            .block();
        // 直接从解析后的对象中提取第一个城市的ID
        if (response != null && response.location != null && !response.location.isEmpty()) {
            return response.location.get(0).id;
        }
        return null;
    } catch (Exception e) {
        throw new RuntimeException("Failed to get city code for: " + city, e);
    }
  }
}

